'use strict';

import Base from './base.js';

export default class extends Base {
    /**
     * index action
     * @return {Promise} []
     */
    async indexAction() {
        // 所有角色集合
        let roles = await this.model("s_role").select();
        return this.success(roles);
    }

    async userAction() {
        let data = {};
        let userId = this.get('userId');

        // 所有角色集合
        let roles = await this.model("s_role").select();

        // 用户已拥有的角色集合
        let checkedRoles = await this.model("s_role").join("s_user_role on s_role.id = s_user_role.roleId").where({userId: userId}).select();

        data.checkedRoles = checkedRoles;
        data.roles = roles;
        return this.success(data);
    }

    async saveAction() {
        let name = this.post("name");
        let description = this.post("description");
        let roleId = await this.model("s_role").thenAdd({name: name, description: description}, {name: name});
        return this.success(roleId);
    }

    async authAction() {
        let roleId = this.post("roleId");
        let authIds = this.post("authIds");
        let count = await this.model("s_role_auth").where({roleId: roleId}).countSelect();
        if (count > 0) {
            await this.model("s_role_auth").update({authId: authIds}, {roleId: roleId});
        } else {
            await this.model("s_role_auth").add({roleId: roleId, authId: authIds});
        }
        return this.success();
    }

}